/**
 * Limit the inputs' value to numbers, and validate the number format
 * E.g. false (no decimal point), false (non-negative number), 0 (decimal digits) for INTEGERS
 *
 * @param e event
 * @param dec whether contain decimal point
 * @param min whether the number shall be non-negative number
 * @param len decimal digits
 * @returns {boolean}
 */
// eslint-disable-next-line max-params
function validDecimal(e, dec, min, len) {
  let keyNum;
  const decSep = ".";
  if (window.event) {
    // IE
    keyNum = e.keyCode;
  } else if (e.which) {
    // Netscape/Firefox/Opera
    keyNum = e.which;
  }

  if (keyNum === 8) {
    // backspace
    return true;
  }

  const obj = e.srcElement || e.target;
  const val = obj.value;

  if (min && keyNum === 45) {
    return val.length === 0;
  }

  if (dec && keyNum === decSep.charCodeAt(0)) {
    if (val.indexOf(decSep) !== -1) {
      return false;
    } else if (val.length === 0) {
      obj.value = "0";
    }

    return true;
  } // decimal

  if (keyNum < 48 || keyNum > 57) {
    return false;
  }

  // decimal len
  if (dec && val.indexOf(decSep) !== -1) {
    const decimalPart = val.substring(val.indexOf(decSep) + 1, val.length);
    if (decimalPart.length >= len) {
      return false;
    }
  }

  return true;
}

// 格式化金额
function formatMoney(number) {
  number = typeof number === "number" ? String(number) : number;
  if (!number) {
    return;
  }
  number = number.replace(/,/g, "");
  if (isNaN(number) || number === "") {
    return "";
  }
  number = Math.round(number * 100) / 100;
  if (number < 0) {
    return (
      "-" +
      outputDollars(Math.floor(Math.abs(number) - 0) + "") +
      outputCents(Math.abs(number) - 0)
    );
  }
  return outputDollars(Math.floor(number - 0) + "") + outputCents(number - 0);
}
function outputDollars(number) {
  if (number.length <= 3) {
    return number === "" ? "0" : number;
  }
  const mod = number.length % 3;
  let output = mod === 0 ? "" : number.substring(0, mod);
  for (let i = 0; i < Math.floor(number.length / 3); i++) {
    if (mod === 0 && i === 0) {
      output += number.substring(mod + 3 * i, mod + 3 * i + 3);
    } else {
      output += "," + number.substring(mod + 3 * i, mod + 3 * i + 3);
    }
  }
  return output;
}
function outputCents(amount) {
  amount = Math.round((amount - Math.floor(amount)) * 100);
  return amount < 10 ? ".0" + amount : "." + amount;
}

// 计算百分比
function calculatePercentage(divisor, dividend, rounding = true) {
  let number = 0;
  if (dividend !== 0) {
    number = divisor / dividend;
  }
  number = number * 100;
  // 判断是否需要保留两位小数
  if (rounding) {
    return number.toFixed(2) + "%";
  }
  return noRoundingAndkeepTwoDecimalPlaces(number) + "%";
}

// 不四舍五入并保留两位小数
function noRoundingAndkeepTwoDecimalPlaces(number) {
  return Math.floor(number * 100) / 100;
}

export default {
  validDecimal,
  formatMoney,
  calculatePercentage,
  noRoundingAndkeepTwoDecimalPlaces,
};

export { formatMoney };
